package com.itheima.test;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class test {
    public static void main(String[] args) {
        //md2加密算法
        String md2Ecode = md2Jdk("hello jdk md");
        System.out.println("MD2JDk加密后为：" + md2Ecode);
        System.out.println("MD2JDk加密后密文长度为：" + md2Ecode.length());
        //md5加密算法
        String md5Ecode = md5Jdk("hello jdk md");
        System.out.println("MD5JDk加密后为：" + md5Ecode);
        System.out.println("MD5JDk加密后密文长度为：" + md5Ecode.length());
    }

    public static String convertByteToHexString(byte[] bytes) {
        String result = "";
        for (int i = 0; i < bytes.length; i++) {
            int temp = bytes[i] & 0xff;
            String tempHex = Integer.toHexString(temp);
            if (tempHex.length() < 2) {
                result += "0" + tempHex;
            } else {
                result += tempHex;
            }
        }
        return result;
    }

    public static String md2Jdk(String message) {
        String temp = "";
        try {
            MessageDigest md2Digest = MessageDigest.getInstance("MD2");
            byte[] encodeMd2Digest = md2Digest.digest(message.getBytes());
            temp = convertByteToHexString(encodeMd2Digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return temp;
    }

    public static String md5Jdk(String message) {
        String temp = "";
        try {
            MessageDigest md5Digest = MessageDigest.getInstance("MD5");
            byte[] encodeMd5Digest = md5Digest.digest(message.getBytes());
            temp = convertByteToHexString(encodeMd5Digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return temp;
    }
}
